package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.DailyOrdersCount;
import com.sky.entity.DailyUserCount;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.*;


import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> dateTimeList = new ArrayList<>();
        dateTimeList.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateTimeList.add(begin);
        }
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateTimeList) {
            //遍历查询date对应营业额
            LocalDateTime beginTime= LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime= LocalDateTime.of(date, LocalTime.MAX);
            //select sum(amount) from orders where status = 5 and order_time > beginTime and order_time < endTime;
            Double turnover = orderMapper.getAmountByDate(beginTime,endTime, Orders.COMPLETED);
            turnover = turnover == null ? 0.0:turnover;
            turnoverList.add(turnover);
        }

        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateTimeList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();

//        List<LocalDate> dateTimeList = new ArrayList<>();
//        dateTimeList.add(begin);
//        LocalDateTime beginTime= LocalDateTime.of(begin, LocalTime.MIN);
//        while(!begin.equals(end)){
//            begin = begin.plusDays(1);
//            System.out.println(begin);
//            dateTimeList.add(begin);
//        }
//        LocalDate endTime= begin;
//        List<Double> turnoverList = orderMapper.getAmountByDate2(begin,endTime,Orders.COMPLETED);
//
//
//        return TurnoverReportVO
//                .builder()
//                .dateList(StringUtils.join(dateTimeList, ","))
//                .turnoverList(StringUtils.join(turnoverList, ","))
//                .build();




    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateTimeList = new ArrayList<>();
        dateTimeList.add(begin);
        LocalDateTime startDateTime = begin.atStartOfDay();
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateTimeList.add(begin);
        }

        // 将日期转换为当天的开始和结束时间
        LocalDateTime endDateTime = begin.atStartOfDay();
        // 调用 Mapper 层查询数据,优化sql查询语句使得只需要查询一次数据库，减少数据库压力
        List<DailyUserCount> dailyCounts = userMapper.getDailyUserCounts(startDateTime, endDateTime);

        // 将查询结果转换为日期到数量的映射
        Map<LocalDate, Integer> dateCountMap = new HashMap<>();
        for (DailyUserCount duc : dailyCounts) {
            dateCountMap.put(duc.getDate(), duc.getCount());
        }

        // 根据日期列表填充结果，保证每天都有值（如果没有数据则为0）
        //查询并记录每日新增的用户数量
        List<Integer> newUserIdList = new ArrayList<>();
        for (LocalDate date : dateTimeList) {
            newUserIdList.add(dateCountMap.getOrDefault(date, 0));
        }
        //记录每日总用户数量
        List<Integer> totalUserIdList = new ArrayList<>();
        Integer totalCount = 0;
        for(int i=0;i<newUserIdList.size();i++){
            totalCount += newUserIdList.get(i);
            totalUserIdList.add(totalCount);
        }
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateTimeList,","))
                .newUserList(StringUtils.join(newUserIdList,","))
                .totalUserList(StringUtils.join(totalUserIdList,","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //获取日期列表
        List<LocalDate> dateTimeList = new ArrayList<>();
        dateTimeList.add(begin);
        LocalDateTime startDateTime = begin.atStartOfDay();
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateTimeList.add(begin);
        }
        //获取订单总数
        LocalDateTime endDateTime = begin.atStartOfDay();
        Integer totalOrders = orderMapper.getTotalOrders(startDateTime,endDateTime,Orders.CONFIRMED);
        //获取有效订单总数
        Integer totalValidOrders = orderMapper.getTotalValidOrders(startDateTime,endDateTime,Orders.COMPLETED);
        //获取有效率
        Double completionRate = (double)totalValidOrders/totalOrders;

        //获取每日订单列表
        List<DailyOrdersCount> ordersList = orderMapper.getDailyOrders(startDateTime,endDateTime,Orders.CONFIRMED);
        // 将查询结果转换为日期到数量的映射
        Map<LocalDate, Integer> dateOrdersCountMap = new HashMap<>();
        for (DailyOrdersCount duc : ordersList) {
            dateOrdersCountMap.put(duc.getDate(), duc.getCount());
        }
        // 根据日期列表填充结果，保证每天都有值（如果没有数据则为0）
        //查询并记录每日订单总数
        List<Integer> dailyOrders = new ArrayList<>();
        for (LocalDate date : dateTimeList) {
            dailyOrders.add(dateOrdersCountMap.getOrDefault(date, 0));
        }

        //获取每日有效订单列表
        List<DailyOrdersCount> validOrdersList = orderMapper.getDailyValidOrders(startDateTime,endDateTime,Orders.COMPLETED);
        // 将查询结果转换为日期到数量的映射
        Map<LocalDate, Integer> dateValidOrdersCountMap = new HashMap<>();
        for (DailyOrdersCount duc : validOrdersList) {
            dateValidOrdersCountMap.put(duc.getDate(), duc.getCount());
        }
        // 根据日期列表填充结果，保证每天都有值（如果没有数据则为0）
        //查询并记录每日订单总数
        List<Integer> dailyValidOrders = new ArrayList<>();
        for (LocalDate date : dateTimeList) {
            dailyValidOrders.add(dateValidOrdersCountMap.getOrDefault(date, 0));
        }


        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateTimeList,","))
                .totalOrderCount(totalOrders)
                .validOrderCount(totalValidOrders)
                .orderCompletionRate(completionRate)
                .orderCountList(StringUtils.join(dailyOrders,","))
                .validOrderCountList(StringUtils.join(dailyValidOrders,","))

                .build();
    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime startDateTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endDateTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> list = orderMapper.getTop10(startDateTime,endDateTime);
        List<Integer> numberList = new ArrayList<>();
        List<String> nameList = new ArrayList<>();
        for (GoodsSalesDTO goods : list) {
            numberList.add(goods.getNumber());
            nameList.add(goods.getName());
        }
        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }
}
